<template>
  <div class="forgot-page">
    <div class="background"></div>
    
    <div class="form-container">
      <h2>重置密码</h2>
      <form @submit.prevent="handleReset">
        <div class="input-group">
          <input 
            v-model="phone"
            placeholder="注册手机号"
            @input="validatePhone"
          >
          <span v-if="phoneError" class="error">{{ phoneError }}</span>
        </div>

        <div class="input-group">
          <input
            v-model="newPassword"
            type="password"
            placeholder="新密码（8位）"
            maxlength="8"
          >
          <span v-if="passwordError" class="error">{{ passwordError }}</span>
        </div>

        <button type="submit">重置密码</button>
        <p class="login-link" @click="goLogin">返回登录</p>
      </form>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { ElMessage } from 'element-plus'

const router = useRouter()
const auth = useAuthStore()

const phone = ref('')
const newPassword = ref('')
const phoneError = ref('')
const passwordError = ref('')
const phoneRegex = /^1[3-9]\d{9}$/

const validatePhone = () => {
  phoneError.value = phoneRegex.test(phone.value)? '' : '无效手机号'
}
const handleReset = () => {
  if (!phoneRegex.test(phone.value)) {
    phoneError.value = '无效手机号'
    return
  }
  if (newPassword.value.length!== 8) {
    passwordError.value = '密码必须为8位'
    return
  }
  try {
    auth.resetPassword(phone.value, newPassword.value)
    ElMessage.success('密码重置成功')
    router.push('/login')
  } catch (error) {
    ElMessage.error(error.message)
  }
}

const goLogin = () => router.push('/login')
</script>

<style scoped>
.forgot-page {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
}

.background {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: url('@/assets/bg.png') no-repeat center/cover;
  filter: blur(3px);
  z-index: -1;
}

.form-container {
  background: rgba(255, 255, 255, 0.9);
  padding: 2rem;
  border-radius: 10px;
  width: 400px;
}

.input-group {
  margin: 1rem 0;
}

input {
  width: 100%;
  padding: 0.8rem;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.error {
  color: #f56c6c;
  font-size: 12px;
}

button[type="submit"] {
  width: 100%;
  padding: 1rem;
  background: #409eff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.login-link {
  text-align: center;
  margin-top: 1rem;
  color: blue;
  cursor: pointer;
}
</style>